<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of imguplauder
 *
 * @author laimis
 */
class ImgUpLauder {


    function uploadPhotos($file,$index,$height,$width){
        if(getimagesize($file['tmp_name'])) {
            $photo_id = mktime();
            if($ext = $this->getPhotoExt($file)){
                $photo = $photo_id .'_'.$index.$ext;
                $this->resizeImage($file['tmp_name'], $height , $width , $ext);
                copy($file['tmp_name'], BASEURL.'photos/' . $photo);
                return $photo;
            }
            return false;
        }
    }

    function getPhotoExt($file)
    {
        $ext = FALSE;
        if ($file['type'] == 'image/gif') {
            $ext = '.gif';
        } else {
            $typeArray = explode('/', $file['type']);
            switch($typeArray[1]) {
                case 'jpg':
                    case 'jpeg':
                        case 'pjjpeg':
                        } // switch
                        $ext = '.jpeg';
                    }
                    return $ext;
                }

                function resizeImage($originalImage,$toWidth,$toHeight, $ext){
                    // Get the original geometry and calculate scales
                    list($width, $height) = getimagesize($originalImage);
                    $xscale = $width / $toWidth;
                    $yscale = $height / $toHeight;
                    // Recalculate new size with default ratio
                    if ($yscale>$xscale){
                        $new_width  = round($width * (1 / $yscale));
                        $new_height = round($height * (1 / $yscale));
                    }
                    else {
                        $new_width  = round($width * (1 / $xscale));
                        $new_height = round($height * (1 / $xscale));
                    }
                    // Resize the original image
                    $imageResized = imagecreatetruecolor($new_width, $new_height);
                    switch ($ext) {
                        case '.jpeg':
                            $imageTmp = imagecreatefromjpeg($originalImage);
                            break;
                        case '.gif':
                            $imageTmp = imagecreatefromgif($originalImage);
                            break;
                    }
                    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    // yrasome sumazinta foto, ant senos...
                    switch ($ext) {
                        case '.jpeg':
                            imagejpeg($imageResized, $originalImage);
                            break;
                        case '.gif':
                            imagegif($imageResized, $originalImage);
                            break;
                    }
                }
            }
            ?>
